import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/bigfontchoosebutton.dart';
import 'package:wayofdressing/components/choosebutton.dart';
import 'package:wayofdressing/components/schedule_box.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/dio/ScheduleDio.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';

class ScheduleScreen extends StatefulWidget {
  const ScheduleScreen({super.key});

  @override
  State<ScheduleScreen> createState() => _ScheduleScreenState();
}

class _ScheduleScreenState extends State<ScheduleScreen> {
  int day = 0;
  int month = 0;
  bool chooseMonth = false;
  bool isLoading = false;
  String weekday = '六';
  List days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  DateTime now = DateTime.now();
  List<Widget> scheduleWidgetList = [];

  @override
  void initState() {
    super.initState();
    day = now.day;
    month = now.month;
    fetchSchedule();
  }

  List<Widget> createScheduleBoxes(Response response) {
    List<Widget> scheduleBoxes = [];
    List<dynamic> data = response.data['data'];
    for (var item in data) {
      scheduleBoxes.add(ScheduleBox(
        date: item['date'],
        content: item['content'],
        outfitName: item['outfitDTO']['name'],
        aiSuggestion: item['aiSuggestion']??'无',
      ));
    }
    if (scheduleBoxes.isEmpty) {
      return [
        SizedBox(
          height: MediaQuery.of(context).size.height / 5,
        ),
        Column(
          children: [
            Icon(
              Icons.hourglass_empty_rounded,
              size: 300,
            ),
            Text(
              '没有日程安排',
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 36,
                  fontWeight: FontWeight.bold),
            )
          ],
        )
      ];
    } else {
      return scheduleBoxes;
    }
  }

  Future<void> fetchSchedule() async {
    setState(() {
      isLoading = true;
    });
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int userId = prefs.getInt('id') ?? 0;
    String date = now.year.toString().padLeft(4, '0') +'-'+
        month.toString().padLeft(2, '0') +'-'+
        day.toString().padLeft(2, '0');
    try {
      Response response = await getScheduleByUserIdAndDate(
        userId: userId,
        date: date,
        dio: dio,
      );
      scheduleWidgetList = createScheduleBoxes(response);
      print('Response data: ${response.data}');
    } catch (e) {
      ShowDialog.showErrorAndDetail(context,'查询失败');
      print('Error: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  List<Widget> dayWidget() {
    List<Widget> list1 = [];
    for (int i = 1; i <= days[month - 1]; i++) {
      var cB = BigFontChooseButton(
          isActive: day,
          text: '$i',
          listNumber: i,
          onPressed: () {
            setState(() {
              day = i;
              weekday = getWeekday();
              fetchSchedule();
            });
          });
      list1.add(cB);
    }
    return list1;
  }

  List<Widget> monthWidget() {
    List<Widget> list1 = [];
    for (int i = 1; i <= 12; i++) {
      var cB = BigFontChooseButton(
          isActive: month,
          text: '$i',
          listNumber: i,
          onPressed: () {
            setState(() {
              month = i;
            });
          });
      list1.add(cB);
    }
    return list1;
  }

  String getWeekday() {
    num sumday = 0;
    for (int i = 1; i < month; i++) {
      sumday += days[i - 1];
    }
    sumday += day;
    sumday %= 7;
    print(sumday);
    switch (sumday) {
      case 1:
        return '一';
      case 2:
        return '二';
      case 3:
        return '三';
      case 4:
        return '四';
      case 5:
        return '五';
      case 6:
        return '六';
      default:
        return '七';
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> dayList = dayWidget();
    List<Widget> monthList = monthWidget();
    return Column(
      children: [
        Expanded(
          flex: 2,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  Row(
                    children: [
                      Container(
                        child: TextButton(
                          style: ButtonStyle(
                              padding: MaterialStatePropertyAll(
                                EdgeInsets.all(0),
                              ),
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(25),
                                ),
                              ),
                              backgroundColor: chooseMonth
                                  ? MaterialStatePropertyAll(Colors.black54)
                                  : MaterialStatePropertyAll(Colors.transparent)),
                          onPressed: () {
                            setState(() {
                              chooseMonth = true;
                              day = 1;
                            });
                          },
                          child: Text(
                            '$month',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                              color: chooseMonth ? Colors.white : Colors.black,
                            ),
                          ),
                        ),
                      ),
                      Text(
                        '月',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Container(
                        child: TextButton(
                          style: ButtonStyle(
                              padding: MaterialStatePropertyAll(
                                EdgeInsets.all(0),
                              ),
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(25),
                                ),
                              ),
                              backgroundColor: !chooseMonth
                                  ? MaterialStatePropertyAll(Colors.black54)
                                  : MaterialStatePropertyAll(Colors.transparent)),
                          onPressed: () {
                            setState(() {
                              chooseMonth = false;
                            });
                          },
                          child: Text(
                            '$day',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                              color: chooseMonth ? Colors.black : Colors.white,
                            ),
                          ),
                        ),
                      ),
                      Text(
                        '日',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  Text(
                    '周' + weekday,
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(),
                ],
              ),
              Container(
                height: 42,
                margin: EdgeInsets.symmetric(horizontal: 30),
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                      spreadRadius: 2, // 阴影扩展半径
                      blurRadius: 5, // 阴影模糊半径
                      offset: Offset(0, 4), // 阴影偏移量
                    ),
                  ],
                  borderRadius: BorderRadius.circular(25),
                  color: Colors.white,
                ),
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: chooseMonth ? monthList : dayList,
                ),
              ),
            ],
          ),
        ),
        Expanded(
          flex: 9,
          child: isLoading
              ? Center(child: CircularProgressIndicator())
              : ListView.builder(
            itemCount: scheduleWidgetList.length,
            itemBuilder: (context, index) {
              return scheduleWidgetList[index];
            },
          ),
        )
      ],
    );
  }
}
